# 获取Makefile所在的目录路径
MAKEFILE_DIR := $(dir $(realpath $(firstword $(MAKEFILE_LIST))))
# 获取项目根目录(Makefile所在目录的父目录)
PROJECT_ROOT := $(realpath $(MAKEFILE_DIR)/..)

# 定义变量 - 使用绝对路径
APP_NAME = myapp
ENTRY_FILE = $(PROJECT_ROOT)/cmd/api/main.go
OUTPUT_DIR = $(PROJECT_ROOT)/bin
DOCS_DIR = $(PROJECT_ROOT)/docs
WINDOWS_OUTPUT = $(OUTPUT_DIR)/windows
LINUX_OUTPUT = $(OUTPUT_DIR)/linux
WINDOWS_BIN = $(WINDOWS_OUTPUT)/$(APP_NAME).exe
LINUX_BIN = $(LINUX_OUTPUT)/$(APP_NAME)
RESOURCE_DIRS = $(PROJECT_ROOT)/static $(PROJECT_ROOT)/templates $(PROJECT_ROOT)/config

# 默认目标
all: win linux docs

# 编译 Windows 64 位程序并复制资源
win: clean_win
	mkdir -p $(WINDOWS_OUTPUT)
	GOOS=windows GOARCH=amd64 go build -o $(WINDOWS_BIN) $(ENTRY_FILE)
	$(foreach dir,$(RESOURCE_DIRS),cp -r $(dir) $(WINDOWS_OUTPUT)/$(notdir $(dir));)

# 编译 Linux 64 位程序并复制资源
linux: clean_linux
	mkdir -p $(LINUX_OUTPUT)
	GOOS=linux GOARCH=amd64 go build -o $(LINUX_BIN) $(ENTRY_FILE)
	$(foreach dir,$(RESOURCE_DIRS),cp -r $(dir) $(LINUX_OUTPUT)/$(notdir $(dir));)

# 编辑docs文件
docs:
	cd $(PROJECT_ROOT) && swag init -g cmd/api/main.go -o docs

# 清理生成的文件
clean: clean_win clean_linux

clean_win:
	rm -rf $(WINDOWS_OUTPUT)

clean_linux:
	rm -rf $(LINUX_OUTPUT)

clean_docs:
	rm -rf $(DOCS_DIR)

# 打包目标 - 创建压缩文件
package_win: win
	cd $(OUTPUT_DIR) && zip -r $(APP_NAME)_windows.zip windows

package_linux: linux
	cd $(OUTPUT_DIR) && tar -czf $(APP_NAME)_linux.tar.gz linux

package: package_win package_linux

# 自定义输出目录
custom_output:
	@if [ -z "$(TARGET_DIR)" ]; then \
		echo "Error: TARGET_DIR is not set. Use 'make -f scripts/Makefile custom_output TARGET_DIR=/path/to/dir'"; \
		exit 1; \
	fi
	mkdir -p $(TARGET_DIR)
	GOOS=$(shell go env GOOS) GOARCH=amd64 go build -o $(TARGET_DIR)/$(APP_NAME)$(shell if [ "$(shell go env GOOS)" = "windows" ]; then echo ".exe"; fi) $(ENTRY_FILE)
	$(foreach dir,$(RESOURCE_DIRS),cp -r $(dir) $(TARGET_DIR)/$(notdir $(dir));) 